package com.newland.mesdk.demo.fragment;

import java.util.concurrent.TimeUnit;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;

import com.newland.mesdk.demo.main.R;
import com.newland.mtype.module.common.externalPin.BaudrateType;
import com.newland.mtype.module.common.externalPin.DataBitType;
import com.newland.mtype.module.common.externalPin.OddEvenCheckType;
import com.newland.mtype.module.common.pin.AccountInputType;
import com.newland.mtype.module.common.pin.EncryptType;
import com.newland.mtype.module.common.pin.KeyManageType;
import com.newland.mtype.module.common.pin.MacAlgorithm;
import com.newland.mtype.module.common.pin.PinInputEvent;
import com.newland.mtype.module.common.pin.StopBitType;
import com.newland.mtype.module.common.pin.WorkingKey;
import com.newland.mtype.module.common.pin.WorkingKeyType;
import com.newland.mtype.module.common.swiper.SwipResult;
import com.newland.mtype.util.Dump;
import com.newland.mtype.util.ISOUtils;
import com.newland.mesdk.demo.interfaceimpl.ExternalPinInputInterfaceImpl;
import com.newland.mesdk.demo.main.MainActivity;
import com.newland.mesdk.demo.main.MyApplication;
import com.newland.mesdk.demo.util.Const;
import com.newland.mesdk.demo.util.Const.MessageTag;

/**
 * Created by YJF 外接
 * 密码键盘模块
 */
public class ExternalPinInputFragment extends Fragment implements OnClickListener {
	private ExternalPinInputInterfaceImpl externalPinInputInterfaceImpl;
	private MainActivity mainActivity;
	protected static final String MAINKEY = "253C9D9D7C2FBBFA253C9D9D7C2FBBFA";// 预设输入值
	protected static final String WORKINGKEY_DATA_MAC = "DBFE96D0A5F09D24";// 预设输入值
	protected static final String WORKINGKEY_DATA_TRACK = "DBFE96D0A5F09D24DBFE96D0A5F09D24";// 预设输入值
	protected static final String WORKINGKEY_DATA_PIN = "D2CEEE5C1D3AFBAF00374E0CC1526C86";// 预设输入值
	private Button btnInit, btnLoadMk, btnLoadWk, btnCalMac;
	private Button btnEncry, btnDecry, btnPinInput, btnCancalPinInput;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_externalpin, null);
		mainActivity = (MainActivity) getActivity();
		initExternalPinView(view);
		return view;
	}

	public void initExternalPinView(View view) {
		btnInit = (Button) view.findViewById(R.id.btn_external_pin_init);
		btnInit.setOnClickListener(this);

		btnLoadMk = (Button) view.findViewById(R.id.btn_external_pin_laodmk);
		btnLoadMk.setOnClickListener(this);

		btnLoadWk = (Button) view.findViewById(R.id.btn_external_pin_loadwk);
		btnLoadWk.setOnClickListener(this);

		btnCalMac = (Button) view.findViewById(R.id.btn_external_pin_calmac);
		btnCalMac.setOnClickListener(this);

		btnEncry = (Button) view.findViewById(R.id.btn_external_pin_encry);
		btnEncry.setOnClickListener(this);

		btnDecry = (Button) view.findViewById(R.id.btn_external_pin_decry);
		btnDecry.setOnClickListener(this);

		btnPinInput = (Button) view.findViewById(R.id.btn_external_pin_pininput);
		btnPinInput.setOnClickListener(this);

		btnCancalPinInput = (Button) view.findViewById(R.id.btn_external_pin_cancle);
		btnCancalPinInput.setOnClickListener(this);

	}

	@Override
	public void onClick(View v) {
		if (mainActivity.isDeviceInit()) {
			if (mainActivity.processingisLocked()) {
				mainActivity.showMessage("请先完成或撤销当前操作...", MessageTag.ERROR);
			} else {
				mainActivity.connectDevice();
				externalPinInputInterfaceImpl = new ExternalPinInputInterfaceImpl();
				switch (v.getId()) {
				case R.id.btn_external_pin_init:
					new Thread(new Runnable() {

						@Override
						public void run() {
							try {
									mainActivity.processingLock();
									mainActivity.showMessage("开始初始化Pinpad口" + "\r\n", MessageTag.TIP);
									externalPinInputInterfaceImpl.pinPadPortInit(BaudrateType.BPS300, DataBitType.DATA_BIT_6, OddEvenCheckType.NO_CHECK,
											StopBitType.STOP_BIT_ONE);
									mainActivity.showMessage("初始化Pinpad口成功！" + "\r\n", MessageTag.NORMAL);
									mainActivity.processingUnLock();

							} catch (Exception e) {
								mainActivity.showMessage("初始化Pinpad口异常：" + e + "\r\n", MessageTag.ERROR);
								mainActivity.processingUnLock();
							}
						}
					}).start();

					break;
				case R.id.btn_external_pin_laodmk:
					new Thread(new Runnable() {

						@Override
						public void run() {
							try {
									mainActivity.processingLock();
									mainActivity.showMessage("开始装载主密钥" + "\r\n", MessageTag.TIP);
									byte[] mainKey = externalPinInputInterfaceImpl.loadMainKey(Const.MKIndexConst.DEFAULT_MK_INDEX, ISOUtils.hex2byte(MAINKEY));
									if (mainKey == null) {
										mainActivity.showMessage("主密钥装载失败!" + "\r\n", MessageTag.NORMAL);
										mainActivity.processingUnLock();
									} else {
										mainActivity.showMessage("主密钥装载成功!" + "\r\n", MessageTag.NORMAL);
										mainActivity.showMessage("主密钥装载返回的数据：" + ISOUtils.hexString(mainKey) + "\r\n", MessageTag.DATA);
										mainActivity.processingUnLock();
									}

							} catch (Exception e) {
								mainActivity.showMessage("外接密码键盘装载一个主密钥异常：" + e + "\r\n", MessageTag.NORMAL);
								mainActivity.processingUnLock();
							}
						}
					}).start();

					break;
				case R.id.btn_external_pin_loadwk:
					new Thread(new Runnable() {

						@Override
						public void run() {
							try {
									mainActivity.processingLock();
									mainActivity.showMessage("开始装载工作密钥" + "\r\n", MessageTag.TIP);
									byte[] wk_pin = externalPinInputInterfaceImpl.loadWorkingKey(WorkingKeyType.PININPUT, Const.MKIndexConst.DEFAULT_MK_INDEX,
											Const.PinWKIndexConst.EXTERNAL_PIN_WK_INDEX, ISOUtils.hex2byte(WORKINGKEY_DATA_PIN));
									if (wk_pin != null) {
										mainActivity.showMessage("pin工作密钥装载成功!" + "\r\n", MessageTag.NORMAL);
									} else {
										mainActivity.showMessage("pin工作密钥装载失败!" + "\r\n", MessageTag.NORMAL);
									}
									byte[] wk_mac = externalPinInputInterfaceImpl.loadWorkingKey(WorkingKeyType.MAC, Const.MKIndexConst.DEFAULT_MK_INDEX,
											Const.MacWKIndexConst.EXTERNAL_MAC_WK_INDEX, ISOUtils.hex2byte(WORKINGKEY_DATA_MAC));
									if (wk_mac != null) {
										mainActivity.showMessage("mac工作密钥装载成功!" + "\r\n", MessageTag.NORMAL);
									} else {
										mainActivity.showMessage("mac工作密钥装载失败!" + "\r\n", MessageTag.NORMAL);
										
									}
									mainActivity.processingUnLock();
							} catch (Exception e) {
								mainActivity.showMessage("外接密码键盘装载一个工作秘钥异常：" + e + "\r\n", MessageTag.ERROR);
								mainActivity.processingUnLock();
							}
						}
					}).start();

					break;
				case R.id.btn_external_pin_calmac:
					new Thread(new Runnable() {

						@Override
						public void run() {
							try {
									mainActivity.processingLock();
									mainActivity.showMessage("开始MAC计算" + "\r\n", MessageTag.TIP);
									byte[] calacMac = externalPinInputInterfaceImpl.calcMac(MacAlgorithm.MAC_X99, new WorkingKey(
											Const.MacWKIndexConst.EXTERNAL_MAC_WK_INDEX), "123456".getBytes("GBK"), 1);
									mainActivity.showMessage("外接密码键盘MAC计算值为：123456" + "\r\n", MessageTag.DATA);
									mainActivity.showMessage("外接密码键盘MAC计算摘要算法：DISPERSE_MAC_ECB" + "\r\n", MessageTag.DATA);
									mainActivity.showMessage("外接密码键盘MAC计算结果为：" + Dump.getHexDump(calacMac) + "\r\n", MessageTag.DATA);
									mainActivity.processingUnLock();

							} catch (Exception e) {
								mainActivity.showMessage("外接密码键盘MAC计算异常：" + e + "\r\n", MessageTag.ERROR);
								mainActivity.processingUnLock();
							}
						}
					}).start();

					break;
				case R.id.btn_external_pin_decry:
					new Thread(new Runnable() {

						@Override
						public void run() {
							try {
									mainActivity.processingLock();
									mainActivity.showMessage("开始解密一串数据" + "\r\n", MessageTag.TIP);
									byte[] decryptData = externalPinInputInterfaceImpl.decrypt(new WorkingKey(Const.MacWKIndexConst.EXTERNAL_MAC_WK_INDEX),
											EncryptType.ENCRYPT_CBC, "A816A5F7C1A085823D95C21DEAA2CBDD".getBytes("GBK"), new byte[] { 0x00, 0x00, 0x00, 0x00,
													0x00, 0x00, 0x00, 0x00 }, 1);
									mainActivity.showMessage("外接密码键盘解密一串数据,数据为：A816A5F7C1A085823D95C21DEAA2CBDD" + "\r\n", MessageTag.DATA);
									mainActivity.showMessage("外接密码键盘解密秘钥为：MAC" + "\r\n", MessageTag.DATA);
									mainActivity.showMessage("外接密码键盘解密模式为：ENCRYPT_CBC" + "\r\n", MessageTag.DATA);
									mainActivity.showMessage("外接密码键盘解密一串数据,解密结果为：" + Dump.getHexDump(decryptData) + "\r\n", MessageTag.DATA);
									mainActivity.processingUnLock();

							} catch (Exception e) {
								mainActivity.showMessage("外接密码键盘解密一串数据异常：" + e + "\r\n", MessageTag.ERROR);
								mainActivity.processingUnLock();
							}

						}
					}).start();

					break;
				case R.id.btn_external_pin_encry:
					new Thread(new Runnable() {

						@Override
						public void run() {
							try {
									mainActivity.processingLock();
									mainActivity.showMessage("开始加密一串数据" + "\r\n", MessageTag.TIP);
									byte[] encryptData = externalPinInputInterfaceImpl.encrypt(new WorkingKey(Const.MacWKIndexConst.EXTERNAL_MAC_WK_INDEX),
											EncryptType.ENCRYPT_CBC, "BF20150912".getBytes("GBK"), new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 },
											1);
									mainActivity.showMessage("外接密码键盘加密一串数据,数据为：BF20150912" + "\r\n", MessageTag.DATA);
									mainActivity.showMessage("外接密码键盘加密秘钥为：MAC" + "\r\n", MessageTag.DATA);
									mainActivity.showMessage("外接密码键盘加密模式为：ENCRYPT_CBC" + "\r\n", MessageTag.DATA);
									mainActivity.showMessage("外接密码键盘加密一串数据,加密结果为：" + ISOUtils.hexString(encryptData) + "\r\n", MessageTag.NORMAL);
									mainActivity.processingUnLock();

							} catch (Exception e) {
								mainActivity.showMessage("外接密码键盘加密一串数据异常：" + e + "\r\n", MessageTag.ERROR);
								mainActivity.processingUnLock();
							}
						}
					}).start();

					break;
				case R.id.btn_external_pin_pininput:
					new Thread(new Runnable() {

						@Override
						public void run() {
							try {
									mainActivity.processingLock();
									SwipResult swipRslt = ((MyApplication) (mainActivity).getApplication()).getSwipResult();
									if (swipRslt == null) {
										mainActivity.showMessage("请先到刷卡模块刷卡！" + "\r\n", MessageTag.TIP);
										mainActivity.processingUnLock();
									} else {
										mainActivity.showMessage("请输入6位密码，并以确认键结束" + "\r\n", MessageTag.TIP);
										PinInputEvent pinInputEvent = externalPinInputInterfaceImpl.startExternalPinInput(new WorkingKey(
												Const.PinWKIndexConst.EXTERNAL_PIN_WK_INDEX), KeyManageType.MKSK, AccountInputType.USE_ACCOUNT, swipRslt
												.getAccount().getAcctNo(), 6, new byte[] { 'F', 'F', 'F', 'F', 'F', 'F', 'F', 'F', 'F', 'F' }, true, 60,
												TimeUnit.SECONDS, 1);
										if (pinInputEvent == null) {
											mainActivity.showMessage("密码输入撤销" + "\r\n", MessageTag.NORMAL);
											mainActivity.processingUnLock();
										} else if (pinInputEvent.isSuccess()) {
											mainActivity.showMessage("密码输入完成" + "\r\n", MessageTag.NORMAL);
											mainActivity.showMessage("密码:" + Dump.getHexDump(pinInputEvent.getEncrypPin()) + "\r\n", MessageTag.DATA);
											mainActivity.processingUnLock();
										}else if(pinInputEvent.isUserCanceled()){
											mainActivity.showMessage("密码输入撤销" + "\r\n", MessageTag.NORMAL);
											mainActivity.processingUnLock();
										}
									}

							} catch (Exception e) {
								mainActivity.showMessage("外接密码键盘调用一个pin输入过程异常：" + e + "\r\n", MessageTag.ERROR);
								mainActivity.processingUnLock();
							}
						}
					}).start();

					break;
				case R.id.btn_external_pin_cancle:
					new Thread(new Runnable() {

						@Override
						public void run() {
							try {
									mainActivity.processingUnLock();
									externalPinInputInterfaceImpl.cancelPinInput();
									mainActivity.showMessage("外接密码键盘撤销上一次密码输入成功！" + "\r\n", MessageTag.NORMAL);
							} catch (Exception e) {
								mainActivity.showMessage("外接密码键盘撤销上一次密码输入异常：" + e + "\r\n", MessageTag.ERROR);
								mainActivity.processingUnLock();
							}
						}
					}).start();

					break;

				default:
					break;
				}
			}
		} else {
			mainActivity.showMessage("设备未初始化，请先初始化！" + "\r\n", MessageTag.NORMAL);
		}
	}

	
}
